#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

struct ListNode 
{
    int val;
    struct ListNode* next;
};

//struct ListNode* removeElements(struct ListNode* head, int val)
//{
//    if (!head)
//        return head;
//
//    struct ListNode* plist = removeElements(head->next, val);
//
//    if (head->val == val)
//    {
//        return plist;
//    }
//    else
//    {
//        head->next = plist;
//        return head;
//    }
//}

struct ListNode* removeElements(struct ListNode* head, int val)
{
    while (head->val == val)
    {
        head = head->next;
    }
    struct ListNode* prev = head;
    while (prev->next)
    {
        if (prev->next->val == val)
        {
            struct ListNode* del = prev->next;
            prev->next = prev->next->next;
            prev = prev->next;
            free(del);
        }
        else
        {
            prev = prev->next;
        }
    }

    return prev;
}
int main()
{
    struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(n1);
    struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(n2);
    struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(n3);
    struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(n4);

    n1->val = 1;
    n2->val = 2;
    n3->val = 3;
    n4->val = 4;

    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = NULL;

    struct ListNode* newhead = removeElements(n1, 3);

    return 0;
}